package com.zeratul.gateway.filter;

import com.zeratul.common.core.constant.MdcConstants;
import com.zeratul.common.trace.TraceIdManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局追踪id生成过滤器
 */
@Component
@Slf4j
public class GlobalTraceIdFilter implements GlobalFilter, Ordered {

    /**
     * 全局追踪生成器
     */
    @Autowired
    private TraceIdManager traceIdManager;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 基于之前的请求，创建新的请求，设置新的请求头
        ServerHttpRequest newRequest = request.mutate()
                .header(MdcConstants.TRACE_ID, traceIdManager.getTraceId())
                .build();
        // 创建新的exchange
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        //放行请求
        return chain.filter(newExchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 20;
    }
}
